package com.yang.refleciton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author yds
 * @program java-annotation-and-reflection
 * @description 获取Class类的信息
 * @create 2020-10-12 11:05
 **/
public class Demo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.yang.entity.User");
        //获得类的名字
        System.out.println(c1.getName());//包名+类名
        System.out.println(c1.getSimpleName());//类名
        //获得类的属性
        System.out.println("--------------------------------------");
        Field[] fields = c1.getFields();//只能找到public修饰的属性
        for (Field field : fields) {
            System.out.println(field);
        }
        fields=c1.getDeclaredFields();//找到全部的属性
        for (Field field : fields) {
            System.out.println(field);
        }
        Field name = c1.getDeclaredField("name");//获取指定属性
        System.out.println(name);
        //获取类的方法
        System.out.println("--------------------------------------");
        Method[] methods = c1.getMethods();//获取的本类和父类的所有方法
        for (Method method : methods) {
            System.out.println("getMethods-->"+method);
        }
        methods=c1.getDeclaredMethods();//获取的本类的所有方法
        for (Method method : methods) {
            System.out.println("getDeclaredMethods-->"+method);
        }
        Method name1 = c1.getMethod("getName", null);//获取类的指定方法
        Method name2 = c1.getMethod("setName", String.class);//获取类的指定方法
        System.out.println("获取name的指定方法"+name1+" "+name2);
        //获取构造器
        System.out.println("--------------------------------------");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        constructors=c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class,int.class);
        System.out.println("指定->"+declaredConstructor);
    }
}